package com.ai.fupincore.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUtil {

	protected static final Log LOGGER = LogFactory.getLog(FtpUtil.class);

	public static final String FILE_SPEARATROR = "/";
	public static final int BIN = 0;
	public static final int ASC = 1;

	private FTPClient client = null;
	private String localPath = null;

	private String host = null;
	private int port = 0;

	private String userName = null;
	private String passWord = null;
	private String remotePath = null;
	private String remotePathHis;// FTP文件历史目录,在cfg_ftp_path表remote_path_his字段配置
	private static String encoding = System.getProperty("file.encoding");

	/**
	 * @param ftpPathCode
	 *            String
	 * @throws DedicException 
	 */
	public FtpUtil(String ftpPathCode) throws DedicException  {

	}

	/**
	 * @param hostIp
	 * @param port
	 * @param username
	 * @param password
	 * @param remotepath
	 * @param localPath2
	 * @param remotePathHis2
	 * @param localPathTemp
	 * @throws IOException 
	 * @throws SocketException 
	 */
	public FtpUtil(String hostIp, int port, String username, String password, String remotepath, String remotePathHis) throws DedicException, SocketException, IOException  {
		LOGGER.debug("hostIp --> " + hostIp + " , port -->" + port + " , username -->" + username + " , password -->" + password + " , remotepath -->" + remotepath
				+ " , remotePathHis -->" + remotePathHis);
		client = new FTPClient();
		client.connect(hostIp, port);
		client.login(username, password);
		client.changeWorkingDirectory(remotepath);
		host = hostIp;
		userName = username;
		passWord = password;
		remotePath = remotepath;
	}
	
	public FtpUtil(String hostIp, int port, String username, String password, String remotepath) throws DedicException, SocketException, IOException  {
		LOGGER.debug("hostIp --> " + hostIp + " , port -->" + port + " , username -->" + username + " , password -->" + password + " , remotepath -->" + remotepath);
		client = new FTPClient();
		client.connect(hostIp, port);
		client.login(username, password);
		client.changeWorkingDirectory(remotepath);
		host = hostIp;
		userName = username;
		passWord = password;
		remotePath = remotepath;
	}
	

	/**
	 * 二进制格式
	 * 
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void bin() throws DedicException, IOException  {
		client.setFileType(FTP.BINARY_FILE_TYPE);
	}

	/**
	 * ascii格式
	 * 
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void asc() throws DedicException, IOException  {
		client.setFileType(FTP.ASCII_FILE_TYPE);
	}

	public FTPClient getFTPClient() {
		return client;
	}

	/**
	 * 列出服务器的目录下面的文件
	 * 
	 * @param encoding
	 *            String
	 * @return String[]
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public String[] list(String encoding) throws DedicException, IOException  {
		List<String> list = new ArrayList<>();

		FTPFile[] ftpFiles = client.listFiles(client.printWorkingDirectory());

		for (int i = 0; i < ftpFiles.length; i++) {
			if (ftpFiles[i].isFile()) {
				list.add(ftpFiles[i].getName());
			}
		}

		return list.toArray(new String[0]);
	}

	/**
	 * 根据pathName列出服务器的目录下的文件
	 * 
	 * @param pathName
	 *            文件名或文件路径
	 * @return 返回FTPFile列表
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public FTPFile[] listFtpFiles(String pathName) throws DedicException, IOException  {
		return client.listFiles(pathName);
	}

	/**
	 * @return String[]
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public String[] list() throws DedicException, IOException  {
		return list("GBK");
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param input
	 *            InputStream
	 * @param mode
	 *            int
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void upload(String remoteFileName, InputStream input, int mode) throws DedicException, IOException  {
		if (mode == BIN) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
		} else if (mode == ASC) {
			client.setFileType(FTP.ASCII_FILE_TYPE);
		} else {
			throw new DedicException ("不支持的传输模式:" + mode);
		}
		upload(remoteFileName, input);
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param input
	 *            InputStream
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void upload(String remoteFileName, InputStream input) throws DedicException, IOException  {
		client.storeFile(remoteFileName, input);
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param localFileName
	 *            String
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void upload(String remoteFileName, String localFileName) throws DedicException, IOException  {
		InputStream is = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(localPath + "/" + localFileName);
			is = new BufferedInputStream(fis);
			client.storeFile(remoteFileName, is);
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (is != null) {
				is.close();
			}
		}
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param localFileName
	 *            String
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void uploadTts(String remoteFileName, String localFileName, int mode) throws DedicException, IOException  {
		if (mode == BIN) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
		} else if (mode == ASC) {
			client.setFileType(FTP.ASCII_FILE_TYPE);
		} else {
			throw new DedicException ("不支持的传输模式:" + mode);
		}
		InputStream is = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(localFileName);
			is = new BufferedInputStream(fis);
			client.storeFile(remoteFileName, is);
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (is != null) {
				is.close();
			}
		}
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param localFileName
	 *            String
	 * @param mode
	 *            int
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void upload(String remoteFileName, String localFileName, int mode) throws DedicException, IOException  {
		if (mode == BIN) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
		} else if (mode == ASC) {
			client.setFileType(FTP.ASCII_FILE_TYPE);
		} else {
			throw new DedicException ("不支持的传输模式:" + mode);
		}
		upload(remoteFileName, localFileName);
	}

	public void uploadWithGzip(String ftpPathCode, String fileNameP, List<?> lines) throws DedicException, IOException  {
		String fileName = fileNameP + ".gz";
		FtpUtil ftpUtil = new FtpUtil(ftpPathCode);
		OutputStream out = ftpUtil.getOutputStream(fileName);
		if (out == null) {
			throw new DedicException ("FTP OutputStream 为空,可能原因FTP未连接或连接超时");
		}
		GZIPOutputStream gzout = null;
		try {
			gzout = new GZIPOutputStream(out);
			IOUtils.writeLines(lines, null, gzout, "GBK");
		} catch (Exception e) {
			throw e;
		} finally {
			if (null != gzout)
				gzout.close();
			out.close();

			ftpUtil.completePendingCommand();
		}
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param output
	 *            OutputStream
	 * @param mode
	 *            int
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void download(String remoteFileName, OutputStream output, int mode) throws DedicException, IOException  {
		if (mode == BIN) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
		} else if (mode == ASC) {
			client.setFileType(FTP.ASCII_FILE_TYPE);
		} else {
			throw new DedicException ("不支持的传输模式:" + mode);
		}
		download(remoteFileName, output);
	}

	/**
	 * 复杂下载,兼容复杂路径
	 * 
	 * @param remoteFileName
	 *            String
	 * @param output
	 *            OutputStream
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void complexDownload(String remoteFileName, OutputStream output) throws DedicException, IOException  {
		// 设置为bin模式
		client.setFileType(FTP.BINARY_FILE_TYPE);

		String filePath = null;
		String downFile = remoteFileName.trim();
		if (downFile.indexOf("\\") >= 0 || downFile.indexOf("/") >= 0) {
			if (downFile.charAt(0) != '.' && downFile.charAt(0) == '/') {
				downFile = "." + downFile;
			} else {
				downFile = "./" + downFile;
			}
			if (downFile.indexOf("\\") > downFile.indexOf("/")) {
				filePath = downFile.substring(0, downFile.lastIndexOf("\\"));
				downFile = downFile.substring(downFile.lastIndexOf("\\") + 1, downFile.length());
			} else {
				filePath = downFile.substring(0, downFile.lastIndexOf("/"));
				downFile = downFile.substring(downFile.lastIndexOf("/") + 1, downFile.length());
			}
		}
		if (null != filePath) {
			this.changeWorkingDirectory(filePath);
		}
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug(client.printWorkingDirectory());
		}

		boolean rtn = client.retrieveFile(new String(downFile.getBytes("GBK"), "iso-8859-1"), output);
		if (!rtn) {
			throw new DedicException ("下载远程文件:" + remoteFileName + ",不成功");
		}
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param output
	 *            OutputStream
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void download(String remoteFileName, OutputStream output) throws DedicException, IOException  {
		String filePath = null;
		String downFile = remoteFileName.trim();
		if (downFile.indexOf("\\") >= 0 || downFile.indexOf("/") >= 0) {
			if (downFile.indexOf("\\") > downFile.indexOf("/")) {
				filePath = downFile.substring(0, downFile.lastIndexOf("\\"));
				downFile = downFile.substring(downFile.lastIndexOf("\\") + 1, downFile.length());
			} else {
				filePath = downFile.substring(0, downFile.lastIndexOf("/"));
				downFile = downFile.substring(downFile.lastIndexOf("/") + 1, downFile.length());
			}
		}
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("文件路径:" + filePath + ",下载文件名:" + downFile);
			LOGGER.debug("当前目录:" + client.printWorkingDirectory());
		}
		if (null != filePath) {
			this.changeWorkingDirectory(filePath);
		}
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("切换到的目录:" + client.printWorkingDirectory());
		}

		boolean rtn = client.retrieveFile(downFile, output);
		if (!rtn) {
			throw new DedicException ("下载远程文件:" + remoteFileName + "不成功！");
		}
	}

	public void downloadSimple(String remoteFileName, OutputStream output) throws DedicException, IOException  {
		boolean rtn = client.retrieveFile(remoteFileName, output);
		if (!rtn) {
			throw new DedicException ("下载远程文件:" + remoteFileName + ",不成功");
		}
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param localFileName
	 *            String
	 * @param mode
	 *            int
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void download(String remoteFileName, String localFileName, int mode) throws DedicException, IOException  {
		if (mode == BIN) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
		} else if (mode == ASC) {
			client.setFileType(FTP.ASCII_FILE_TYPE);
		} else {
			throw new DedicException ("不支持的传输模式:" + mode);
		}
		download(remoteFileName, localFileName);
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param localFileName
	 *            String
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void download(String remoteFileName, String localFileName) throws DedicException, IOException  {
		OutputStream os = null;
		String filePath = "";
		FileOutputStream fos = null;
		try {
			if (null != localPath && !"".equals(localPath)) {
				filePath = localPath + "/" + localFileName;
			} else {
				filePath = localFileName;
			}
			fos= new FileOutputStream(filePath);
			os = new BufferedOutputStream(fos);
			boolean rtn = client.retrieveFile(remoteFileName, os);
			if (!rtn) {
				throw new DedicException ("下载远程文件:" + remoteFileName + ",不成功");
			}
		} finally {
			if (fos != null) {
				fos.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param localFileName
	 *            String
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void downloadTts(String remoteFileName, String localFileName, int mode) throws DedicException, IOException  {
		OutputStream os = null;
		FileOutputStream fos = null;
		if (mode == BIN) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
		} else if (mode == ASC) {
			client.setFileType(FTP.ASCII_FILE_TYPE);
		} else {
			throw new DedicException ("不支持的传输模式:" + mode);
		}
		try {
			fos = new FileOutputStream(localFileName);
			os = new BufferedOutputStream(fos);
			boolean rtn = client.retrieveFile(remoteFileName, os);
			if (!rtn) {
				throw new DedicException ("下载远程文件:" + remoteFileName + ",不成功");
			}
		} finally {
			if (fos != null) {
				fos.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @return InputStream
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public InputStream readRemote(String remoteFileName) throws DedicException, IOException  {
		
		client.setFileType(FTP.BINARY_FILE_TYPE);

		return client.retrieveFileStream(remoteFileName);
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @param mode
	 *            int
	 * @return InputStream
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public InputStream readRemote(String remoteFileName, int mode) throws DedicException, IOException  {
		if (mode == BIN) {
			client.setFileType(FTP.BINARY_FILE_TYPE);
		} else if (mode == ASC) {
			client.setFileType(FTP.ASCII_FILE_TYPE);
		} else {
			throw new DedicException ("不支持的传输模式:" + mode);
		}
		return readRemote(remoteFileName);
	}

	/**
	 * @param oldRemoteFileName
	 *            String
	 * @param newRemoteFileName
	 *            String
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void rename(String oldRemoteFileName, String newRemoteFileName) throws DedicException, IOException  {
		client.rename(oldRemoteFileName, newRemoteFileName);
	}

	/**
	 * @param remoteFileName
	 *            String
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public  void delete(String remoteFileName) throws DedicException, IOException  {
		boolean rtn = client.deleteFile(remoteFileName);
		if (!rtn) {
			throw new DedicException ("删除远程文件:" + remoteFileName + ",不成功");
		}
	}

	/**
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void completePendingCommand() throws DedicException, IOException  {
		client.completePendingCommand();
	}

	/**
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void close() throws DedicException, IOException  {
		if (client.isConnected()) {
			client.disconnect();
		}
	}

	/**
	 * @throws DedicException 
	 * @throws IOException 
	 * @throws SocketException 
	 */
	public void reconnect() throws DedicException, SocketException, IOException  {
		if (!client.isConnected()) {
			client = new FTPClient();
			client.connect(host, port);
			client.login(userName, passWord);
			client.changeWorkingDirectory(remotePath);

		}
	}

	/**
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void forceReconnect() throws DedicException, IOException  {
		if (!client.isConnected()) {
			client.disconnect();
		}

		client = new FTPClient();
		client.connect(host, port);
		client.login(userName, passWord);
		client.changeWorkingDirectory(remotePath);

	}

	/**
	 * 获得输入流
	 * 
	 * @param
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public OutputStream getOutputStream(String fileName) throws DedicException, IOException  {
		return client.storeFileStream(fileName);
	}

	/**
	 * 将远程文件移动至远程历史目录
	 * 
	 * @param fileName
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void moveFileToRemoteHisDir(String fileName) throws DedicException, IOException  {
		if (client.listFiles(fileName).length == 0) {
			throw new DedicException ("在远程服务器上未找到文件" + fileName + ",文件移动至历史目录失败");
		}
		StringBuilder newFileName = new StringBuilder();
		newFileName.append(getRemotePathHis());
		newFileName.append(FILE_SPEARATROR);
		newFileName.append(fileName);
		rename(fileName, newFileName.toString());
	}

	/**
	 * 获取远程文件历史目录
	 * 
	 * @return
	 * @throws com.ai.appframe2.common.Exception
	 * 
	 */
	public String getRemotePathHis() throws DedicException  {
		if (remotePathHis == null || remotePathHis.length() < 1) {
			throw new DedicException ("未配置远程文件历史目录");
		}
		return remotePathHis;
	}

	public String getWorkingDirectory() throws DedicException, IOException  {
		if (this.client != null) {
			return this.client.printWorkingDirectory();
		}
		return null;
	}

	public void changeWorkingDirectory(String pathName) throws DedicException, IOException  {
		if (this.client != null) {
			this.client.changeWorkingDirectory(pathName);
		}
	}


	public String getRemotePath() {
		return remotePath;
	}

	/**
	 * 向已有文件里面追加数据
	 * 
	 * @param remoteName
	 * @param in
	 * @return
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public boolean appendFile(String remoteName, InputStream in) throws DedicException, IOException  {
		return client.appendFile(remoteName, in);
	}

	/**
	 * 切换到指定目录(不存在就创建目录同时切换到新建的目录)
	 * 
	 * @param directoryId
	 * @throws DedicException 
	 * @throws IOException 
	 */
	public void changeToRightDir(String directoryId) throws DedicException, IOException  {
		if (client != null) {
			String ftpDir = client.printWorkingDirectory();
			if (ftpDir == null) {
				ftpDir = "/";
			}

			String curDir;// = null;

			if (directoryId.startsWith("/")) {
				curDir = directoryId;
			} else {
				if (!ftpDir.endsWith("/")) {
					curDir = ftpDir + FILE_SPEARATROR + directoryId;
				} else {
					curDir = ftpDir + directoryId;
				}
			}

			boolean flag = client.changeWorkingDirectory(curDir);
			if (!flag) {
				client.makeDirectory(directoryId);
				client.changeWorkingDirectory(curDir);
			}
		}
	}

	public boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) {
		boolean result = false;

		try {
			int reply;
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			client.connect(url);
			// ftp.connect(url, port);// 连接FTP服务器
			// 登录
			client.login(username, password);
			client.setControlEncoding(encoding);
			// 检验是否连接成功
			reply = client.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				client.disconnect();
				return result;
			}

			// 转移工作目录至指定目录下
			if(client.isAvailable()){
				client.makeDirectory(path);
			}
			boolean change = client.changeWorkingDirectory(path);
			//设置二进制传输模式
			client.setFileType(FTP.BINARY_FILE_TYPE);
			if (change) {
				result = client.storeFile(filename, input);
				if (result) {
					LOGGER.info("上传成功!");
				}
			}
			input.close();
			client.logout();
		} catch (IOException e) {
			LOGGER.error(e);
		} finally {
			if (client.isConnected()) {
				try {
					client.disconnect();
				} catch (IOException ioe) {
					LOGGER.error(ioe);
				}
			}
		}
		return result;
	}

	/**
	 * 根据文件名获得盘符
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getDisk(String fileName) {
		String[] temps = fileName.split(":");
		if (null != temps && temps.length > 0) {
			return temps[0];
		}
		return "";
	}

	/**
	 * @param ip
	 * @param port
	 * @param userName
	 * @param userPwd
	 * @param path
	 * @throws SocketException
	 * @throws IOException
	 *             function:连接到服务器
	 */
	public void connectServer(String ip, int port, String userName, String userPwd, String path) {
		client = new FTPClient();
		try {
			// 连接
			client.connect(ip, port);
			// 登录
			client.login(userName, userPwd);
			if (path != null && path.length() > 0) {
				// 跳转到指定目录
				client.changeWorkingDirectory(path);
			}
		} catch (SocketException e) {
			LOGGER.error(e);
		} catch (IOException e) {
			LOGGER.error(e);
		}
	}

	/**
	 * @throws IOException
	 *             function:关闭连接
	 */
	public  void closeServer() {
		if (client.isConnected()) {
			try {
				client.logout();
				client.disconnect();
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
	}

	/**
	 * @param path
	 * @return function:读取指定目录下的文件名
	 * @throws IOException
	 */
	public List<String> getFileList(String path) {
		List<String> fileLists = new ArrayList<>();
		// 获得指定目录下所有文件名
		FTPFile[] ftpFiles = null;
		try {
			ftpFiles = client.listFiles(path);
		} catch (IOException e) {
			LOGGER.error(e);
		}
		for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
			FTPFile file = ftpFiles[i];
			if (file.isFile()) {
				fileLists.add(file.getName());
			}
		}
		return fileLists;
	}

	/**
	 * @param fileName
	 * @param sourceFile
	 * @return
	 * @throws IOException
	 *             function:下载文件
	 */
	public boolean unloadFile(String fileName, String sourceFile) {
		boolean flag = false;
		try {
			FileOutputStream fos = new FileOutputStream(fileName);
			flag = client.retrieveFile(sourceFile, fos);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			flag = false;
			LOGGER.error(e);
		}
		return flag;
	}

	/**
	 * 返回一个文件流
	 * 
	 * @param fileName
	 * @return
	 */
	public String readFile(String fileName) {
		String result = "";
		InputStream ins = null;
		try {
			ins = client.retrieveFileStream(fileName);

			BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
			String inLine = reader.readLine();
			while (inLine != null) {
				result += (inLine + System.getProperty("line.separator"));
				inLine = reader.readLine();
			}
			reader.close();
			if (ins != null) {
				ins.close();
			}

			// 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
			client.getReply();
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return result;
	}

	/**
	 * Description: 从FTP服务器下载文件
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param remotePath
	 *            FTP服务器上的相对路径
	 * @param fileName
	 *            要下载的文件名
	 * @param localPath
	 *            下载后保存到本地的路径
	 * @return
	 */
	public boolean downFile(String url, int port, String username, String password, String remotePath, String fileName, String localPath) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		OutputStream is = null;
		FileOutputStream fos = null;
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());

					fos = new FileOutputStream(localFile);
					is = fos;
					ftp.retrieveFile(ff.getName(), is);
				}
			}

			ftp.logout();
			success = true;
		} catch (IOException e) {
			LOGGER.error(e);
		} finally {
			if(fos !=null){
				try {
					fos.close();
				} catch (IOException e) {
					LOGGER.error(e);
				}
			}
			if(is !=null){
				try {
					is.close();
				} catch (IOException e) {
					LOGGER.error(e);
				}
			}
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					LOGGER.error(ioe);
				}
			}
		}
		return success;
	}

	public boolean deleteFile(String url, int port, String username, String password, String remotePath, String fileName) throws DedicException  {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();

			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					ftp.deleteFile(fileName);
				}

			}

			ftp.logout();
			success = true;
		} catch (IOException e) {
			LOGGER.error(e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					LOGGER.error(ioe);
				}
			}
		}
		return success;
	}
}
